package mp

import (
	"duoke/context"
	"duoke/internal/dao"
	"duoke/internal/model/entity"
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/request"
	"duoke/utils/response"
	"duoke/utils/yaml"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

var Coupon = new(couponCtl)

type couponCtl struct{}

// 创建商户支付订单
func (ctl *couponCtl) MerchantPayCreate(c *gin.Context) {
	req := request.JsonMap(c)
	orderNo := gconv.String(req["orderNo"])
	if orderNo == "" {
		response.Error(c, "订单号缺失", nil)
		return
	}
	var order *entity.Coupon
	err := dao.Coupon.Ctx(c).Where("order_no", orderNo).Where("status", 0).Scan(&order)
	if err != nil || order == nil {
		response.Error(c, "订单不存在", nil)
		return
	}
	user, err := dao.User.Ctx(c).Where("id", order.UserId).One()
	if err != nil || user.IsEmpty() {
		response.Error(c, "用户不存在", nil)
		return
	}
	config := yaml.GetConfig()
	SubMchId := gconv.String(user.Map()["sub_mch_id"])
	if config.SubMch.SubType == "2" {
		SubMchId = ""
	}
	// 获取支付参数
	notifyUrl := context.Global.Domain + "/mp/notify/merchant_coupon_pay"
	payConf, err := service.WechatPay.OrderV2(c, notifyUrl, gconv.String(user.Map()["openid"]), order.OrderNo, float32(order.PayAmount)/100,
		"create coupon", SubMchId)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{
		"pay":   payConf,
		"order": order,
	})
}

// 创建用户支付订单
func (ctl *couponCtl) UserPayCreate(c *gin.Context) {
	req := request.JsonMap(c)
	orderNo := gconv.String(req["orderNo"])
	if orderNo == "" {
		response.Error(c, "订单号缺失", nil)
		return
	}
	var order *entity.CouponOrder
	err := dao.CouponOrder.Ctx(c).Where("order_no", orderNo).Where("pay_status", 0).Scan(&order)
	if err != nil || order == nil {
		response.Error(c, "订单不存在或已超时关闭，请刷新页面重新下单", nil)
		return
	}
	// 查询优惠券的sub_mch_id
	one, err := dao.Coupon.Ctx(c).Where("id", order.CouponId).One()
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// end
	user, err := dao.User.Ctx(c).Where("id", order.UserId).Fields("openid,sub_mch_id").One()
	if err != nil || user.IsEmpty() {
		response.Error(c, "用户不存在", nil)
		return
	}
	SubMchId := gconv.String(one.Map()["sub_mch_id"])
	config := yaml.GetConfig()
	if config.SubMch.SubType == "2" {
		SubMchId = ""
	}
	// 获取支付参数
	notifyUrl := context.Global.Domain + "/mp/notify/user_coupon_pay"
	payConf, err := service.WechatPay.OrderV2(c, notifyUrl, gconv.String(user.Map()["openid"]), order.OrderNo,
		float32(order.PayAmount)/100, "buy coupon", SubMchId)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	go func() {
		err = service.SeparateAccountsSub.BindUser(c, model.ReqSeparateAccountsSub{
			SubMchId: gconv.String(one.Map()["sub_mch_id"]),
			Account:  gconv.String(user.Map()["openid"]),
			Type:     "PERSONAL_OPENID",
		})
	}()
	response.Success(c, "success", gin.H{
		"pay":   payConf,
		"order": order,
	})
}
func (ctl *couponCtl) Behavior(c *gin.Context) {
	req := request.JsonMap(c)
	app := gconv.String(req["app"])
	gid := gconv.Int(req["gid"])
	action := gconv.String(req["action"])
	userR, _ := service.Request.User(c)
	user, err := service.User.Info(c, "id,nickname,avatar,name,phone")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if action == "share_app_message" {
		_, _ = dao.Coupon.Ctx(c).Where("id", gid).Increment("share_app_message", 1)
	}
	if action == "share_timeline" {
		_, _ = dao.Coupon.Ctx(c).Where("id", gid).Increment("share_timeline", 1)
	}
	behavior := new(tables.Behavior)
	behavior.App = app
	behavior.GoodsId = gid
	behavior.UserId = userR.Id
	behavior.Nickname = user.Nickname
	behavior.Avatar = user.Avatar
	behavior.Action = action
	behavior.ViewTime = gconv.Int(req["view_time"])
	behavior.ViewPercentage = gconv.Int(req["view_percentage"])
	affected, err := orm.Db.Insert(behavior)
	if affected == 0 || err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", nil)
}
func (ctl *couponCtl) Copy(c *gin.Context) {
	req := request.JsonMap(c)
	cpType := gconv.Int(req["copy_type"]) // cpType 1视频 2优惠券
	id := gconv.Int(req["id"])
	info, err := service.User.Info(c, "id,phone")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	copy_id, err := service.CopyCs.InfoByCopyId(id, "id,copy_id,copy_type,user_id")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if copy_id.UserId == info.Id {
		if cpType == 1 {
			response.Error(c, "该视频已复制", nil)
		} else {
			response.Error(c, "该优惠券已复制", nil)
		}
		return
	}
	var user_id int
	if cpType == 2 {
		var coupon *tables.Coupon
		err := dao.Coupon.Ctx(c).Where("id", id).Scan(&coupon)
		if err != nil {
			response.Error(c, err.Error(), nil)
			return
		}
		if coupon == nil {
			response.Error(c, "优惠券不存在", nil)
			return
		}
		if coupon.UserId == info.Id {
			response.Error(c, "不能复制自己的优惠券", nil)
			return
		}
		user_id = coupon.UserId
		coupon.UserId = info.Id
		coupon.Id = 0
		// 添加
		_, err = dao.Coupon.Ctx(c).Insert(&coupon)
		if err != nil {
			response.Error(c, err.Error(), nil)
			return
		}
	} else {
		var shortvideo *tables.Shortvideo
		err = dao.Shortvideo.Ctx(c).Where("id", id).Scan(&shortvideo)
		if err != nil {
			response.Error(c, err.Error(), nil)
			return
		}
		if shortvideo == nil {
			response.Error(c, "该短视频不存在", nil)
			return
		}
		if shortvideo.IsFeel == 2 {
			// 等于1
			response.Error(c, "该视频为收费视频", nil)
			return
		}
		if shortvideo.UserId == info.Id {
			response.Error(c, "不能复制自己的短视频", nil)
			return
		}
		user_id = shortvideo.UserId
		shortvideo.UserId = info.Id
		shortvideo.Id = 0
		shortvideo.StoreTel = info.Phone
		// 添加
		_, err = dao.Shortvideo.Ctx(c).Insert(&shortvideo)
		if err != nil {
			logrus.Info("短视频错误", err)
			response.Error(c, err.Error(), nil)
			return
		}
	}
	go func() {
		cs := tables.CopyCs{
			CopyId:   id,
			UserId:   info.Id,
			FromId:   user_id,
			CopyType: cpType,
		}
		_, err = dao.CopyCs.Ctx(c).Insert(&cs)
		if err != nil {
			logrus.Info("短视频错误", err)
			response.Error(c, err.Error(), nil)
			return
		}
	}()
	response.Success(c, "success", nil)
}
func (ctl *couponCtl) List(c *gin.Context) {
	req := request.JsonMap(c)
	price := gconv.Float64(req["price"])
	list, err := service.Coupon.List(c, price)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", list)
}
